/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package spynx.desl.impl;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

import spynx.desl.Argument;
import spynx.desl.DeslPackage;
import spynx.desl.DeslPattern;
import spynx.desl.MatchStatement;
import spynx.desl.PatternExpression;
import spynx.desl.runtime.IExecutionContext;
import spynx.desl.runtime.IPatternMatchInfo;
import spynx.desl.runtime.matchinfos.impl.PatternMatchInfo;
import spynx.util.ArgumentSet;
import spynx.util.DeslRuntimeUtil;
import spynx.util.PatternMismatchedException;

/**
 * <!-- begin-user-doc -->
 * An implementation of the model object '<em><b>Match Statement</b></em>'.
 * <!-- end-user-doc -->
 * <p>
 * The following features are implemented:
 * <ul>
 *   <li>{@link spynx.desl.impl.MatchStatementImpl#getPattern <em>Pattern</em>}</li>
 * </ul>
 * </p>
 *
 * @generated
 */
public class MatchStatementImpl extends ExpressionImpl implements MatchStatement {
	/**
	 * The cached value of the '{@link #getPattern() <em>Pattern</em>}' containment reference.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @see #getPattern()
	 * @generated
	 * @ordered
	 */
	protected PatternExpression pattern;

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected MatchStatementImpl() {
		super();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return DeslPackage.Literals.MATCH_STATEMENT;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public PatternExpression getPattern() {
		return pattern;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public NotificationChain basicSetPattern(PatternExpression newPattern, NotificationChain msgs) {
		PatternExpression oldPattern = pattern;
		pattern = newPattern;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, DeslPackage.MATCH_STATEMENT__PATTERN, oldPattern, newPattern);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public void setPattern(PatternExpression newPattern) {
		if (newPattern != pattern) {
			NotificationChain msgs = null;
			if (pattern != null)
				msgs = ((InternalEObject)pattern).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - DeslPackage.MATCH_STATEMENT__PATTERN, null, msgs);
			if (newPattern != null)
				msgs = ((InternalEObject)newPattern).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - DeslPackage.MATCH_STATEMENT__PATTERN, null, msgs);
			msgs = basicSetPattern(newPattern, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, DeslPackage.MATCH_STATEMENT__PATTERN, newPattern, newPattern));
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case DeslPackage.MATCH_STATEMENT__PATTERN:
				return basicSetPattern(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case DeslPackage.MATCH_STATEMENT__PATTERN:
				return getPattern();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case DeslPackage.MATCH_STATEMENT__PATTERN:
				setPattern((PatternExpression)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case DeslPackage.MATCH_STATEMENT__PATTERN:
				setPattern((PatternExpression)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case DeslPackage.MATCH_STATEMENT__PATTERN:
				return pattern != null;
		}
		return super.eIsSet(featureID);
	}

	@Override
	public Object execute(IExecutionContext context) {
		IPatternMatchInfo p = DeslRuntimeUtil.getMatchInfo(context);
		DeslPattern pattern = (DeslPattern) getPattern().execute(context);
		
		ArgumentSet options = new ArgumentSet(new ArrayList<Argument>());
		options.getArguments().addAll(pattern.getArguments());
		options.getArguments().addAll(getChildren(Argument.class));
		
		options.resolveArgumentValues(context);
		
		int minOccur = options.getArgument(context, "minOccur", 1);
		int maxOccur = options.getArgument(context, "maxOccur", 1);
		boolean returnLastOccur = maxOccur == 1 || options.getArgument(context, "returnLastOccurrenceOnly", true);
		
		int occurence = 0;	
		IPatternMatchInfo lastMatchInfo = null;
		List<IPatternMatchInfo> matchedList = null; 
		try {
			if (!returnLastOccur)
				matchedList = new ArrayList<IPatternMatchInfo>();
			do {
				lastMatchInfo = singleMatch(context, options, p, pattern, lastMatchInfo != null ? lastMatchInfo.getEndLocation() : 0);
				occurence++;
				if (!returnLastOccur) 
					matchedList.add(lastMatchInfo);
				
			} while (occurence < maxOccur && lastMatchInfo.isMatched());
			
		} catch (RuntimeException e) {
			// get cause
			Throwable cause = e;
			while (cause.getCause() != null) cause = cause.getCause();
			
			if (cause instanceof PatternMismatchedException) {
				if (occurence < minOccur)
					throw new PatternMismatchedException(
							String.format("Pattern '%s' is matched only %d time(s), while expected %d times.", 
									 pattern.getName(), occurence, minOccur), e);
			}
			else 
				throw new RuntimeException(String.format("Error matching patternn %s", pattern.getName()), e);
		}
		
		return returnLastOccur ? (lastMatchInfo != null ? lastMatchInfo : PatternMatchInfo.FALSE_MATCHED) :
					matchedList;
	}
	
	private IPatternMatchInfo singleMatch(IExecutionContext context, ArgumentSet options, IPatternMatchInfo parentMatchInfo, DeslPattern pattern, int lastEndLocation) {
		// create a child context for this pattern
		IExecutionContext childContext = context.createChildContext();
		// create a MatchInfo for this pattern
		IPatternMatchInfo matchInfo = pattern.getReturnType() != null ? (
							IPatternMatchInfo)pattern.getReturnType().unwrap(childContext) : new PatternMatchInfo();
		matchInfo.setPattern(pattern);
		matchInfo.setArguments(options);
		
		CharSequence input = (CharSequence) context.resolveValue(options.getArgument(childContext, "input", null));
		if (input == null)
			input = parentMatchInfo.getInput();
		boolean useParentInput = input == parentMatchInfo.getInput();
		int beginPos = options.getArgument(childContext, "position", useParentInput ? parentMatchInfo.getPosition() : lastEndLocation);
		if (useParentInput && !options.getArgument(childContext, "globalPosition", false))
			beginPos += parentMatchInfo.getBeginLocation();
		int endPos = useParentInput ? parentMatchInfo.getEndLocation() : -1;
		
		matchInfo.setInput(input);
		matchInfo.setBeginLocation(beginPos);
		matchInfo.setEndLocation(endPos);
		
		
		// create 'this' entry in the context
		DeslRuntimeUtil.setMatchInfo(childContext, matchInfo);
		//childContext.createVariable("arguments", options);
		//childContext.Variables().addVariable("@this", matchInfo);
		matchInfo.setReturnedResult(pattern.execute(childContext, null));
		
		// update the parentMatchInfo position
		if (useParentInput && options.getArgument(childContext, "updateParentPosition", true)) {
			parentMatchInfo.updateEndLocation(matchInfo.getEndLocation());
			parentMatchInfo.setPosition(matchInfo.getEndLocation(), IPatternMatchInfo.SEEK_GLOBAL_FROM_BEGIN);
		}
		return matchInfo;
	}
} //MatchStatementImpl
